package com.zoe.onelink.feign.decode;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.zoe.onelink.common.model.ApiResult;
import com.zoe.onelink.feign.util.FeignDecoderUtil;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * <p>标题: Feign内部调用异常解码器 暂时使用默认,后续配合状态码做改造</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-07-06
 */
@Slf4j
@RequiredArgsConstructor
public class OnelinkFeignErrorDecoder extends ErrorDecoder.Default {

    @Override
    public Exception decode(String methodKey, Response response) {
        ApiResult<?> apiResult;
        try {
            if (response.body() == null) {
                apiResult = null;
            } else {
                String respText = IoUtil.read(response.body().asReader(StandardCharsets.UTF_8));
                apiResult = JSON.parseObject(respText, ApiResult.class);
            }
        } catch (IOException e) {
            log.error("Decode feignError failure:{}", e.getMessage());
            apiResult = null;
        }
        if (apiResult == null) {
            return super.decode(methodKey, response);
        }
        return FeignDecoderUtil.createInnerApiEx(response, apiResult);
    }

}
